<?php
declare(strict_types=1);

namespace App\Task;

use App\Model\Article;
use App\Model\ArticleAuthor;
use App\Model\ArticleContent;
use App\Model\ArticleSync;
use App\Model\Category;

class SyncArticleTask extends AbstractBaseTask
{
    public function execute(): void
    {
        $columnMap = $this->_getColumnMap();
        if (!$columnMap) {
            $this->logger->warning('栏目对应关系获取失败');
            return;
        }

        $succ = 0;
        foreach ($columnMap as $columnId => $catId) {
            $lists = $this->api->getArticleList($columnId, 1, 20);
            if (empty($lists) || empty($lists['data']['records'])) {
                continue;
            }
            $contentIds = array_column($lists['data']['records'], 'contentId');
            $collectionIds = ArticleSync::query()->whereIn('target_contentid', $contentIds)->get()->pluck('target_contentid')->toArray();
            usort($lists['data']['records'], function ($a, $b) {
                return $a['timestamp'] - $b['timestamp'];
            });
            foreach ($lists['data']['records'] as $article) {
                if (in_array($article['contentId'], $collectionIds)) {
                    continue;
                }
                $authorInfo = $this->_getAuthorInfo($article);
                if (!$authorInfo) {
                    continue;
                }
                $info = Article::create([
                    'catid' => $catId,
                    'title' => $article['title'],
                    'thumb' => $article['imageDescription']['url'] ?? '',
                    'image_list' => new_json_encode($article['imageList'] ?? []),
                    'keywords' => $article['contentColumn'],
                    'description' => mb_substr(trim(strip_tags($article['content'])), 0, 200),
                    'hits' => $article['readCount'],
                    'digg' => $article['praiseCount'],
                    'tags' => new_json_encode([$article['contentColumn']]),
                    'source' => 2,
                    'author_id' => $authorInfo['id'],
                    'add_time' => time(),
                    'edit_time' => time(),
                    'sync_time' => time(),
                ]);
                if ($info) {
                    $succ++;
                    ArticleContent::create([
                        'contentid' => $info['id'],
                        'content' => $article['content']
                    ]);
                    ArticleAuthor::query()->where('id', $authorInfo['id'])->increment('total_article');
                    ArticleSync::create([
                        'target_contentid' => $article['contentId'],
                        'contentid' => $info['id'],
                        'sync_time' => time()
                    ]);
                }
            }
            unset($lists);
        }
        $this->logger->warning(sprintf('成功同步 %s 篇文章', $succ));
    }

    /**
     * 获取作者信息
     * @param $article
     * @return false|array
     */
    private function _getAuthorInfo($article): false|array
    {
        $author = ArticleAuthor::query()->where('name', $article['authorName'])->first();
        if (!$author) {
            $author = ArticleAuthor::create([
                'name' => $article['authorName'],
                'avatar' => $article['authorPic'],
            ]);
            if (!$author) {
                return false;
            }
        }
        return $author->toArray();
    }

    /**
     * 获取栏目对应关系
     * @return false|array
     */
    private function _getColumnMap(): false|array
    {
        $overview = $this->api->getArticleOverview();
        if (!$overview || $overview['code'] != '0000' || empty($overview['data']['contentColumnList'])) {
            return false;
        }
        $category = Category::query()->get(['id', 'catname'])->toArray();
        if (empty($category)) {
            return false;
        }
        $localColumn = array_combine(array_column($category, 'id'), array_column($category, 'catname'));
        $map = [];
        foreach ($overview['data']['contentColumnList'] as $col) {
            $cid = array_search($col['name'], $localColumn);
            if ($cid) {
                $map[$col['id']] = $cid;
            }
        }
        return $map;
    }
}